package com.meitianhui.convenitenbuy.service;


import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.util.FileUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;

import java.io.File;

public class UpdateService extends Service {
    private DownloadManager manager;
    private DownloadCompleteReceiver receiver;
    private String url;
    private String DOWN_PATH = "/ConvenientPurChase/apk/";

    private void initDownManager() {
        manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        receiver = new DownloadCompleteReceiver();
        DownloadManager.Request down = new DownloadManager.Request(Uri.parse(url));
        down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
                | DownloadManager.Request.NETWORK_WIFI);
        down.setAllowedOverRoaming(false);
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
        down.setMimeType(mimeString);
        down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        down.setVisibleInDownloadsUi(true);
        down.setDestinationInExternalPublicDir(DOWN_PATH, "ConvenientPurChase.apk");
        down.setTitle("领有惠");
        manager.enqueue(down);
        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        url = intent.getStringExtra("download_url");
        TipUtils.showToast(App.getInstance(),"下载中，请在通知栏查看！");
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + DOWN_PATH + "ConvenientPurChase.apk";
        File file = new File(path);
        if (file.exists()) {
            boolean isdel = FileUtils.deleteFile(path);
            Log.i("mylog", "删除旧的apk");
        }
        try {
            initDownManager();
        } catch (Exception e) {
            e.printStackTrace();
        }
//        return super.onStartCommand(intent, flags, startId);
        return Service.START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    @Override
    public void onDestroy() {
        if (receiver != null)
            unregisterReceiver(receiver);
        super.onDestroy();
    }

    class DownloadCompleteReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                if (manager.getUriForDownloadedFile(downId) != null) {
//                    installAPK(manager.getUriForDownloadedFile(downId),context);
                    Log.i("mylog", "aa");
                    installAPK(context);
                } else {
                    TipUtils.showToast(App.getInstance(),"下载失败");
                }
                UpdateService.this.stopSelf();
            }
        }

        private void installAPK(Context context) {
            try {
                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + DOWN_PATH + "ConvenientPurChase.apk";
                File file = new File(path);
                if (file.exists()) {
                    File apkFile = new File(path);
                    if (!apkFile.exists()) {
                        return;
                    }
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    //判断是否是AndroidN以及更高的版本
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        Uri contentUri = FileProvider.getUriForFile(context, "com.meitianhui.convenitenbuy.FileProvider", apkFile);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        i.setDataAndType(contentUri, "application/vnd.android.package-archive");
                    } else {
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        i.setDataAndType(Uri.parse("file://" + apkFile.toString()), "application/vnd.android.package-archive");
                    }
                    startActivity(i);
                } else {
                    TipUtils.showToast(App.getInstance(),"下载失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                TipUtils.showToast(App.getInstance(),"没有找到打开此类文件的程序");
            }
        }
    }


    public void openFile(File var0, Context var1) {
        Intent var2 = new Intent();
        var2.addFlags(268435456);
        var2.setAction("android.intent.action.VIEW");
        String var3 = getMIMEType(var0);
        var2.setDataAndType(Uri.fromFile(var0), var3);
        try {
            var1.startActivity(var2);
        } catch (Exception var5) {
            var5.printStackTrace();
            Toast.makeText(var1, "没有找到打开此类文件的程序", Toast.LENGTH_SHORT).show();
        }

    }

    public String getMIMEType(File var0) {
        String var1 = "";
        String var2 = var0.getName();
        String var3 = var2.substring(var2.lastIndexOf(".") + 1, var2.length()).toLowerCase();
        var1 = MimeTypeMap.getSingleton().getMimeTypeFromExtension(var3);
        return var1;
    }

}
